<?php
/**
 * Created by PhpStorm.
 * User: peter
 * Date: 2018/9/18
 * Time: 上午11:45
 */

namespace app\club\logic;


use extend\Functions;
use extend\STATUS_CODE;

class AMap
{
    /**
     * @purpose 通过地址获取经纬度
     * @param string $address
     * @return array
     */
    public static function getLocationByAddress (string $address, string $city = ''): array
    {
        if (!$address) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '请输入详细地址'
            );
        }
        // https://restapi.amap.com/v3/geocode/geo
        // https://restapi.amap.com/v3/geocode/regeo
        $result     = \Requests::get('https://restapi.amap.com/v3/geocode/geo?city='.$city.'&address='.$address.'&key='.config('app.amap.key'));
//        $result     = \Requests::get('https://restapi.amap.com/v3/place/text?city='.$city.'&keywords='.$address.'&key='.config('app.amap.key'));
        $result     = json_decode($result->body, true);
//        return $result;
        if ((int) $result['status'] === 0) {
            return Functions::result(
                STATUS_CODE::FAIL,
                $result['info']
            );
        }
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result['geocodes']
        );
    }

    /**
     * @purpose 通过经纬度获取详细地址
     * @param string $lat
     * @param string $lng
     * @return array
     */
    public static function getAddressByLocation (string $location): array
    {
        if (!$location) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '参数错误'
            );
        }
        $url  = 'https://restapi.amap.com/v3/geocode/regeo?key='.config('app.amap.key').'&location='.$location;
        $result     = \Requests::get($url);
        $result     = json_decode($result->body, true);
        if ((int) $result['status'] === 0) {
            return Functions::result(
                STATUS_CODE::FAIL,
                $result['info']
            );
        }
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result['regeocode']
        );
    }
}